jQuery ->
  dialog = $("#role_user_create")

  notify_show = (message) ->
    $(".notify", dialog).html(message)
    $(".notify", dialog).show()

  dialog.delegate "form", "submit", (e) ->
    e.preventDefault()

    name = $("input.name", dialog).val()
    if $.isEmptyObject(name)      
      notify_show "名称不能为空！"
      return 

    $.ajax
      url: "/admins/groups"
      type: "POST"
      data: $("form", dialog).serialize()
      success: (html) ->
        $(".user_role table tr.no_data").remove()
        $(".user_role table>tbody").prepend(html)
        dialog.modal('hide');
        $("form", dialog)[0].reset()
      error: (data) ->
        try
          notify_show JSON.parse(data.responseText).join('<br/>')
        catch error
          notify_show data.responseText
      
  .on "click", "button.save", ->
    $("form", dialog).submit()


  $(".user_role").on "click", "table>tbody>tr", (e) ->
    url = $(e.currentTarget).attr("data-show-url")
    $.ajax
      url: url
      type: "get"
      success: (html) ->
        $(".user_permission table>tbody").html(html)
  .on "click", "table>tbody .edit", (e) ->
    e.preventDefault()
    url = $(e.currentTarget).attr("href")
    $.ajax
      url: url
      dataType: "script"


  edit_notify_show = (message, dialog) ->
    $(".notify", dialog).html(message)
    $(".notify", dialog).show()

  $("body").on "submit", ".user_group_edit form", (e) ->
    e.preventDefault()
    $form = $(e.currentTarget)
    url = $form.attr("action")
    id = $form.attr("data-value-id")
    edit_dialog = $("##{id}_user_group_edit")

    name = $("input.name", edit_dialog).val()
    if $.isEmptyObject(name)      
      edit_notify_show "名称不能为空！", edit_dialog
      return 

    $.ajax
      url: url
      type: "PUT"
      data: $form.serialize()
      success: (data) ->       
        $(".user_role table td.#{data.id}_group_name").html(data.name)
        edit_dialog.modal("hide")

      error: (data) ->
        console.log("....")
        try
          edit_notify_show JSON.parse(data.responseText).join("<br />"), edit_dialog
        catch error
          edit_notify_show data.responseText, edit_dialog

  .on "click", ".user_group_edit button.save", (e) ->
    $btn = $(e.currentTarget)
    id = $btn.attr("data-value-id")
    edit_dialog = $("##{id}_user_group_edit")
    $("form", edit_dialog).submit()

